#include <irrlicht.h>
#include "MyEventReceiver.h"

#include <windows.h>
#include <scrnsave.h>
#include <commctrl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
using namespace std;

#ifdef UNICODE
#pragma comment(lib, "scrnsavw.lib")
#else
#pragma comment(lib, "scrnsave.lib")
#endif
#pragma comment(lib, "comctl32.lib")

using namespace irr;
using namespace core;
using namespace scene;
using namespace video;
using namespace io;
using namespace gui;


bool button_Checked()
{
  return true;
}

bool createAnimation()
{
  MyEventReceiver receiver;

  IrrlichtDevice *device = createDevice(video::EDT_OPENGL, dimension2d<u32>(640, 480), 32, true, false, true, &receiver);

  if (!device)
    return 1;

  device->setWindowCaption(L"Screen Saver");
  device->getCursorControl()->setVisible(false);

  IVideoDriver* driver = device->getVideoDriver();
  ISceneManager* smgr = device->getSceneManager();

  IAnimatedMesh* mesh = smgr->getMesh("../media/faerie.md2");

  if (!mesh)
  {
    device->drop();
    return 1;
  }
  IAnimatedMeshSceneNode* node = smgr->addAnimatedMeshSceneNode(mesh);

  if (node)
  {
    node->setMaterialFlag(EMF_LIGHTING, false);
    node->setMD2Animation(scene::EMAT_STAND);
    node->setMaterialTexture(0, driver->getTexture("../media/faerie2.bmp"));
  }

  smgr->addCameraSceneNode(0, vector3df(0, 30, -40), vector3df(0, 5, 0));

  while (device->run())
  {
    driver->beginScene(true, true, SColor(255, 100, 101, 140));

    smgr->drawAll();
    driver->endScene();

    

    if (receiver.MouseState.LeftButtonDown || receiver.MouseState.RightButtonDown || receiver.KeyState.KeyIsDown)
    {
      break;
    }
    //if (receiver.MouseState.MouseMoved)
    //  device->drop();
  }
  device->drop();

  return 0;
}

void writeToFile(char* wm_case)
{
  ofstream myfile;
  myfile.open("example.txt");
  myfile << __TIMESTAMP__;
  myfile << wm_case;
  myfile.close();
}





LRESULT WINAPI ScreenSaverProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
  switch (message)
  {
  case WM_CREATE:
    createAnimation(); // irrlicht
    writeToFile("Create");
    break;
  case WM_PAINT:
  {
                 PAINTSTRUCT ps;
                 HDC hdc = BeginPaint(hwnd, &ps);
                 FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1));
                 EndPaint(hwnd, &ps);
  }
  case WM_DESTROY:
    writeToFile("Destroy");
    DestroyWindow(hwnd);
    PostQuitMessage(0);
    return 0;
    break;
  case WM_TIMER:
    writeToFile("Timer");
    break;
  default:
    return DefScreenSaverProc(hwnd, message, wParam, lParam);
  }
  return 0;
}

BOOL WINAPI ScreenSaverConfigureDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
  return TRUE;
}

BOOL WINAPI RegisterDialogClasses(HANDLE hInst)
{
  return TRUE;
}



